package com.wjj.common.mybatis.config;

import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.datasource.DataSourceManager;
import com.mybatisflex.core.datasource.processor.DelegatingDataSourceProcessor;
import com.mybatisflex.spring.boot.MyBatisFlexCustomizer;
import com.mybatisflex.spring.datasource.processor.SpelExpressionDataSourceProcessor;
import com.wjj.common.mybatis.core.domain.BaseEntity;
import com.wjj.common.mybatis.listener.MybatisInsertListener;
import com.wjj.common.mybatis.listener.MybatisUpdateListener;

/**
 * mybatis-flex配置类
 *
 * @author Lion Li
 */
public class MybatisFlexConfig implements MyBatisFlexCustomizer {

    public MybatisFlexConfig() {
        DelegatingDataSourceProcessor dataSourceProcessor = DelegatingDataSourceProcessor.with(
            // Spel 表达式的
            new SpelExpressionDataSourceProcessor()
        );
        // 实例 setter 赋值
        DataSourceManager.setDataSourceProcessor(dataSourceProcessor);
    }

    @Override
    public void customize(FlexGlobalConfig flexGlobalConfig) {

        // 设置全局逻辑删除字段
        flexGlobalConfig.setLogicDeleteColumn("del_flag");
        flexGlobalConfig.setDeletedValueOfLogicDelete("2");
        flexGlobalConfig.setNormalValueOfLogicDelete("0");

        // 设置自动注入监听器
        MybatisInsertListener mybatisInsertListener = new MybatisInsertListener();
        MybatisUpdateListener mybatisUpdateListener = new MybatisUpdateListener();
        flexGlobalConfig.registerInsertListener(mybatisInsertListener, BaseEntity.class);
        flexGlobalConfig.registerUpdateListener(mybatisUpdateListener, BaseEntity.class);
    }
}
